//
//  MLNavigationController.m
//  MultiLayerNavigation
//
//  Created by Feather Chan on 13-4-12.
//  Copyright (c) 2013年 Feather Chan. All rights reserved.
//


#import "MLNavigationController.h"
#import <QuartzCore/QuartzCore.h>
#import "AppDelegate.h"
#import "ParentController.h"


@interface MLNavigationController ()
{
    CGPoint startTouch;
    
    UIImageView *lastScreenShotView;
    UIView *blackMask;
    
    
}

@property (nonatomic,retain) UIView *backgroundView;
@property (nonatomic,retain) NSMutableArray *screenShotsList;

@property (nonatomic,assign) BOOL isMoving;
@end

@implementation MLNavigationController
@synthesize recognizer;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        self.screenShotsList = [[NSMutableArray alloc]initWithCapacity:2];
        self.canDragBack = YES;
        
    }
    return self;
}

- (void)dealloc
{
    self.screenShotsList = nil;
    [self.backgroundView removeFromSuperview];
    self.backgroundView = nil;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.screenShotsList = [[NSMutableArray alloc]initWithCapacity:2];
    self.canDragBack = YES;
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getDetailScrollNoti:) name:kDetailView_ScrollBackNoti object:nil];
}

- (void)getDetailScrollGestureAction:(UIPanGestureRecognizer *)gesture startPoint:(CGPoint)aPoint
{
    _isMoving = YES;
    startTouch = aPoint;
    [self paningGestureReceive:gesture];
    
}


-(void)addNavPanGesture{
    if (!recognizer) {
        
        recognizer = [[UIPanGestureRecognizer alloc]initWithTarget:self
                                                            action:@selector(paningGestureReceive:)];
        recognizer.delegate = self;
        [recognizer delaysTouchesBegan];
        [self.view addGestureRecognizer:recognizer];
    }
}

-(void)removeNavPanGesture{
    if (recognizer) {
        NSLog(@"remowwwwwwwwwwwwwwww");
        [self.view removeGestureRecognizer:recognizer];
        recognizer=nil;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)replaceCaptureImage:(UIImage *)image index:(NSInteger)index{
    if( index > self.screenShotsList.count -1)
        return;
    
    if (!image) {
        return;
    }
    
    NSLog(@"replaceCaptureImage change...");
    
    [self.screenShotsList replaceObjectAtIndex:index withObject:image];
    
}

// override the push method
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if ([self.viewControllers count] > 0) {
        [self.screenShotsList addObject:[self capture]];
    }
    
    if (self.viewControllers.count > 0) {
        viewController.hidesBottomBarWhenPushed = YES;
    }
    [super pushViewController:viewController animated:animated];
}

- (void)removePusherWhenPushViewController:
(UIViewController *)viewController direction:(BOOL)fromtop{
    
    //    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
    //    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    //    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    //    UIGraphicsEndImageContext();
    
    //    UIColor *bgColor = [UIColor colorWithPatternImage:img];
    
    //    UIWindow *window = [[UIApplication sharedApplication]delegate].window;
    ////    UIImageView *imgView = [[UIImageView alloc]initWithFrame:window.bounds];
    ////    imgView.image=img;
    ////    [window addSubview:imgView];
    //    [window setBackgroundColor:[UIColor whiteColor]];
    //    [window setTintColor:[UIColor whiteColor]];
    
    [super popViewControllerAnimated:NO];
    
    CATransition *animation = [CATransition animation];
    [animation setDuration:0.5];
    [animation setType: kCATransitionMoveIn];
    if (fromtop) {
        [animation setSubtype: kCATransitionFromBottom];
    }else{
        [animation setSubtype: kCATransitionFromTop];
    }
    
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    
    [self.view.layer addAnimation:animation forKey:nil];
    [super pushViewController:viewController animated:NO];
    
}

- (void)removePusherWhenPushViewController:
                (UIViewController *)viewController
                    Animated:(BOOL)animated{
    [super popViewControllerAnimated:NO];
    [super pushViewController:viewController animated:animated];

}

// override the pop method
- (UIViewController *)popViewControllerAnimated:(BOOL)animated
{
    [self.screenShotsList removeLastObject];
    return [super popViewControllerAnimated:animated];
}



#pragma mark - Utility Methods -

// get the current view screen shot
- (UIImage *)capture
{
    //    AppDelegate *delegate=[[UIApplication sharedApplication]delegate];
    //
    //    UIGraphicsBeginImageContextWithOptions(delegate.window.bounds.size, delegate.window.opaque, 0.0);
    
    //    return nil;
    //    DZTabController *dztar=[self DZTabController];
    
    //modify by yangq,为了适配融云第三方的一些页面
    UIViewController *lastPushVC = [self.viewControllers objectAtIndex:[self.viewControllers count]-1];
    UITabBarController *dztar=self.tabBarController;
    UIViewController *capture = nil;
    if ([lastPushVC isKindOfClass:[ParentController class]]) {
        ParentController *pusher = (ParentController *)lastPushVC;
        capture = pusher.firstControllerInTabController? dztar:self;
    }else{
        capture = self;
    }
    
    /*
    UITabBarController *dztar=self.tabBarController;
    
    ParentController *pusher=[self.viewControllers objectAtIndex:[self.viewControllers count]-1];
    UIViewController *capture= pusher.isInTabbarController? dztar:self;
    */
    
    //opaque 一定要设置为NO
    UIGraphicsBeginImageContextWithOptions(capture.view.bounds.size, NO, 0.0);
    [capture.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return img;
}

// set lastScreenShotView 's position and alpha when paning
- (void)moveViewWithX:(float)x
{
//        DLog(@"Move to:%f",x);
    
//    //试图打开右侧抽屉
//    if (x<-80) {
//        [recognizer setCancelsTouchesInView:YES];
//        return;
//    }
    
    //    if (x<0) {
    //        [self tryPanToRightDrawer:recognizer];
    //    }
    
    NSLog(@"hthththththththttthththht:%.2f",x);
    x = x>320?320:x;
    x = x<0?0:x;
    
    CGRect frame = self.view.frame;
    frame.origin.x = x;
    self.view.frame = frame;
    
    float scale = (x/6400)+0.95;
    float alpha = 0.4 - (x/800);
    
    lastScreenShotView.transform = CGAffineTransformMakeScale(scale, scale);
    blackMask.alpha = alpha;
    
}


#pragma mark - Gesture Recognizer -
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    if (self.navigationInConverSation) {
        return YES;
    }
    
    return NO;

}
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
//    NSLog(@"WWWWWWPWPWPWPWPPWPWPWPPW :%@",gestureRecognizer.view.class);
    return YES;
}

//- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
//{
//    UIView *tempView = [touch.view superview];
//    if ([tempView isKindOfClass:[MPMediaPlayerView class]]) {
//        return NO;
//    }
//    if (tempView) {
//        if ([tempView superview]) {
//            if ([tempView.superview isKindOfClass:[MPMediaPlayerView class]]) {
//                return NO;
//            }
//        }
//        
//    }
//    
//    NSLog(@"wuwuwuwuwuwuuwuw :%@ AND %@ AND %@",touch.view.class,tempView.class,tempView.superview.class);
//
//    return YES;
//}

- (void)paningGestureReceive:(UIPanGestureRecognizer *)recoginzer
{
    if (blackgroundView.superview) {
        [blackgroundView removeFromSuperview];
    }
    // If the viewControllers has only one vc or disable the interaction, then return.
    if (self.viewControllers.count <= 1 || !self.canDragBack) return;
    
    // we get the touch position by the window's coordinate
    CGPoint touchPoint = [recoginzer locationInView:KEY_WINDOW];
    
    // begin paning, show the backgroundView(last screenshot),if not exist, create it.
    
    
    if (!self.backgroundView) {
        [self.view endEditing:YES];
       
        [self prepareToAnimated];
    }
    
    if (recoginzer.state == UIGestureRecognizerStateBegan) {
        NSLog(@"mlpan src,recoginzer = begin**************");
        
        if (self.navigationInEdite) {
            CGPoint translatedPoint = [recoginzer translationInView:self.view];
            NSLog(@"yoyoyoyoyooyoyoy:%.2f",translatedPoint.x);
            if (translatedPoint.x < 0) {
                self.isLeftDrag = true;
            }else{
                self.isLeftDrag = false;
//                [[NSNotificationCenter defaultCenter] postNotificationName:kEditeOverNoti object:nil];
            }
        }
        
        if (self.isLeftDrag) {
//            [[NSNotificationCenter defaultCenter] postNotificationName:kEditeGesturePassNoti object:recognizer];
        }else{
        
            [self.view endEditing:YES];
//            [[NSNotificationCenter defaultCenter] postNotificationName:kEndSearchEditNoti object:nil];
            
            _isMoving = YES;
            startTouch = touchPoint;
            
            [self prepareToAnimated];
        }
        //End paning, always check that if it should move right or move left automatically
    }
    else if (recoginzer.state == UIGestureRecognizerStateEnded){
        if (self.isLeftDrag) {
          //  [[NSNotificationCenter defaultCenter] postNotificationName:kEditeGesturePassNoti object:recognizer];
        }else{
            [self mlnavigationPanEnded:recoginzer];
            
            if (touchPoint.x - startTouch.x <= 0){
                
                //从上往下滑
                if (fabs(touchPoint.x - startTouch.x) <50 &&
                    touchPoint.y - startTouch.y>20)  {
                    
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
                    
                    if ([self.topViewController respondsToSelector:@selector(swipeDownToDoSomething)]) {
                        [self.topViewController performSelector:@selector(swipeDownToDoSomething) withObject:nil];
                    }
#pragma clang diagnostic pop
                    
                    
                }//从下往上滑
                else if (fabs(touchPoint.x - startTouch.x) <50 &&
                         startTouch.y - touchPoint.y>20){
                    
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
                    if ([self.topViewController respondsToSelector:@selector(swipeUpToDoSomething)]) {
                        [self.topViewController performSelector:@selector(swipeUpToDoSomething) withObject:nil];
                    }
#pragma clang diagnostic pop
                    
                }
                
            }
            //从右侧往左侧滑动
            else{
                if (touchPoint.x - startTouch.x > 50)
                {
                    //执行pop
//                    [[NSNotificationCenter defaultCenter] postNotificationName:kViewWillBeClosedNoti object:nil];
                    [UIView animateWithDuration:0.3 animations:^{
                        [self moveViewWithX:320];
                    } completion:^(BOOL finished) {
                        
                        [self popViewControllerAnimated:NO];
                        CGRect frame = self.view.frame;
                        frame.origin.x = 0;
                        self.view.frame = frame;
                        
                        _isMoving = NO;
                        
                        [self removeBkView];
                    }];
                }
                else
                {
                    //向右侧滑动，就滑动了一点，恢复原样
                    [UIView animateWithDuration:0.3 animations:^{
                        [self moveViewWithX:0];
                    } completion:^(BOOL finished) {
                        _isMoving = NO;
                        [self removeBkView];
                        
                        
                    }];
                    
                }
                
            }
            
            return;
            
        }
        
        // cancal panning, alway move to left side automatically
    }
    else if (recoginzer.state == UIGestureRecognizerStateCancelled){
        if (self.isLeftDrag) {
          //  [[NSNotificationCenter defaultCenter] postNotificationName:kEditeGesturePassNoti object:recognizer];
        }else{
        
            DLog(@"cancel");
            [self mlnavigationPanEnded:recoginzer];
            
            [UIView animateWithDuration:0.3 animations:^{
                [self moveViewWithX:0];
            } completion:^(BOOL finished) {
                _isMoving = NO;
                
                //            self.backgroundView.hidden = YES;
                [self removeBkView];
                
            }];
            
            return;
        }
        
       
    }
    
 
    if (self.isLeftDrag) {

    }else{
    
        if (_isMoving) {
            [self moveViewWithX:touchPoint.x - startTouch.x];
        }
    }
    
}

- (void)setBlackGroundViewAction:(BOOL)isShow
{
    if (isShow) {
        if (!blackgroundView) {
            blackgroundView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
            blackgroundView.backgroundColor = [UIColor blackColor];
        }
        if (blackgroundView.superview) {
            [blackgroundView removeFromSuperview];
        }
        
        [self.view.superview insertSubview:blackgroundView belowSubview:self.view];
        
    }else{
    
        [blackgroundView removeFromSuperview];
    }
    
    

}


-(void)prepareToAnimated{
    //基本工作
    if (!self.backgroundView)
    {
        CGRect frame = self.view.frame;
        
        self.backgroundView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width , frame.size.height)];
        [self.view.superview insertSubview:self.backgroundView belowSubview:self.view];
        
        blackMask = [[UIView alloc]initWithFrame:CGRectMake(0, 0, frame.size.width , frame.size.height)];
        blackMask.backgroundColor = [UIColor blackColor];
        [self.backgroundView addSubview:blackMask];
        self.backgroundView.backgroundColor=[UIColor blackColor]; //新增加的不理解以前的为什么不加
    }
    
    self.backgroundView.hidden = NO;
    
    if (lastScreenShotView){
        [lastScreenShotView removeFromSuperview];
        lastScreenShotView=nil;
    }
    
    UIImage *lastScreenShot = [self.screenShotsList lastObject];
    lastScreenShotView = [[UIImageView alloc]initWithImage:lastScreenShot];
    [self.backgroundView insertSubview:lastScreenShotView belowSubview:blackMask];
    NSLog(@"totototottoottotoeeeeeeeeeeee");
}

-(void)popScaleTransitionAnimated{
    
    [self.view endEditing:YES];
    [self prepareToAnimated];
    [self moveViewWithX:0.0];
    
    //  促成动画
    [UIView animateWithDuration:0.5 animations:^{
        [self moveViewWithX:320.0];
    } completion:^(BOOL finished) {
        
        [self popViewControllerAnimated:NO];
        CGRect frame = self.view.frame;
        frame.origin.x = 0;
        self.view.frame = frame;
        
        _isMoving = NO;
        
        [self removeBkView];
    }];
    
    
}

-(void)removeBkView{
    
    [blackMask removeFromSuperview];
    blackMask=nil;
    
    [self.backgroundView removeFromSuperview];
    self.backgroundView=nil;
}

/*
 检测到手指向左滑动，试图去打开右侧抽屉
 此函数只针对详情页有效
 */

//-(void)tryPanToRightDrawer:(UIPanGestureRecognizer *)pan{
//    if ([self.topViewController isKindOfClass:[NewsDetailViewController class]]) {
//        //
//        
//        NewsDetailViewController *newsdetail = self.topViewController;
//        [newsdetail passPanRecognier:pan];
//    }
//}


-(void)mlnavigationPanEnded:(UIPanGestureRecognizer *)pan{
 
 #pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundeclared-selector"
        
    if ([self.topViewController respondsToSelector:@selector(mlnavigationPanEnded:)]) {
        [self.topViewController performSelector:@selector(mlnavigationPanEnded:) withObject:pan];
        }
#pragma clang diagnostic pop
 }

@end
